<!DOCTYPE html>
<html>

<head>
  <title>Quarkus Dependency Injection</title>
  <script id="adobe_dtm" src="https://www.redhat.com/dtm.js" type="text/javascript"></script>
  <script src="/assets/javascript/highlight.pack.js" type="text/javascript"></script>
  <META HTTP-EQUIV='Content-Security-Policy' CONTENT="default-src 'none'; script-src 'self' 'unsafe-eval' 'sha256-ANpuoVzuSex6VhqpYgsG25OHWVA1I+F6aGU04LoI+5s=' 'sha256-ipy9P/3rZZW06mTLAR0EnXvxSNcnfSDPLDuh3kzbB1w=' js.bizographics.com https://www.redhat.com assets.adobedtm.com jsonip.com https://ajax.googleapis.com https://www.googletagmanager.com https://www.google-analytics.com https://use.fontawesome.com; style-src 'self' https://fonts.googleapis.com https://use.fontawesome.com; img-src 'self' *; media-src 'self' ; frame-src https://www.googletagmanager.com https://www.youtube.com; frame-ancestors 'none'; base-uri 'none'; object-src 'none'; form-action 'none'; font-src 'self' https://use.fontawesome.com https://fonts.gstatic.com;">
  <META HTTP-EQUIV='X-Frame-Options' CONTENT="DENY">
  <META HTTP-EQUIV='X-XSS-Protection' CONTENT="1; mode=block">
  <META HTTP-EQUIV='X-Content-Type-Options' CONTENT="nosniff">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="Quarkus: Supersonic Subatomic Java">
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:site" content="@QuarkusIO"> 
  <meta name="twitter:creator" content="@QuarkusIO">
  <meta property="og:url" content="https://quarkus.io/blog/quarkus-dependency-injection/" />
  <meta property="og:title" content="Quarkus Dependency Injection" />
  <meta property="og:description" content="Quarkus: Supersonic Subatomic Java" />
  <meta property="og:image" content="/assets/images/quarkus_card.png" />
  <link rel="canonical" href="https://quarkus.io/blog/quarkus-dependency-injection/">
  <link rel="shortcut icon" type="image/png" href="/favicon.ico" >
  <link rel="stylesheet" href="https://quarkus.io/guides/stylesheet/config.css" />
  <link rel="stylesheet" href="/assets/css/main.css" />
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">
  <link rel="alternate" type="application/rss+xml"  href="https://quarkus.io/feed.xml" title="Quarkus">
  <script src="https://quarkus.io/assets/javascript/goan.js" type="text/javascript"></script>
  <script src="https://quarkus.io/assets/javascript/hl.js" type="text/javascript"></script>
</head>

<body class="post">
  <!-- Google Tag Manager (noscript) -->
  <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-NJWS5L"
  height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
  <!-- End Google Tag Manager (noscript) -->

  <div class="nav-wrapper">
  <div class="grid-wrapper">
    <div class="width-12-12">
      <input type="checkbox" id="checkbox" />
      <nav id="main-nav" class="main-nav">
  <div class="container">
    <div class="logo-wrapper">
      
        <a href="/"><img src="/assets/images/quarkus_logo_horizontal_rgb_600px_reverse.png" class="project-logo" title="Quarkus"></a>
      
    </div>
    <label class="nav-toggle" for="checkbox">
      <i class="fa fa-bars"></i>
    </label>
    <div id="menu" class="menu">
      <span>
        <a href="/get-started/" class="">Get Started</a>
      </span>
      <span>
        <a href="/guides/" class="">Guides</a>
      </span>
      <span>
        <a href="/community/" class="">Community</a>
      </span>
      <span>
        <a href="/support/" class="">Support</a>
      </span>
      <span>
        <a href="/blog/" class="active">Blog</a>
      </span>
      <span>
        <a href="https://code.quarkus.io" class="button-cta secondary white">Start Coding</a>
      </span>
    </div>
  </div>
      </nav>
    </div>
  </div>
</div>

  <div class="content">
    <div class="post-page grid-wrapper">
  <div class="width-8-12 width-12-12-m doc-content">
    <div class="grid-wrapper">
      <div class="width-12-12">
        <p>
          <a href="/blog"><i class="fas fa-angle-left"></i> Back to all posts</a>
        </p>
      </div>
      <div class="width-12-12">
        <div class="post-date">
          July 24, 2019 
          
            <span class="tags"><a href="/blog/tag/extension">#extension</a><a href="/blog/tag/arc">#arc</a><a href="/blog/tag/development-tips">#development-tips</a></span>
          
        </div>
        <h1 class="post-title">Quarkus Dependency Injection</h1>
        <div class="grid-wrapper">
          <div class="width-8-12 width-12-12-m byline-wrapper">
            
            
              <img class="headshot" src="https://www.gravatar.com/avatar/8036ef0e54eaf768510dcc9be07762a6">
            
            <p class="byline">By Martin Kouba</p>
          </div>
          <div class="width-12-12">
              <div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>Quarkus ArC is a build-time oriented dependency injection based on <a href="http://cdi-spec.org/">CDI 2.0</a>.
In this blogpost, we&#8217;re going to explain the relationship to the specification and describe some of the benefits and drawbacks of the build-time processing design.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="compatibility"><a class="anchor" href="#compatibility"></a>Compatibility</h2>
<div class="sectionbody">
<div class="paragraph">
<p>It does not make sense to reinvent the wheel, especially when it comes to dependency injection.
There are many frameworks that try to solve similar problems.
A year ago, we made a design decision to build Quarkus DI on top of CDI.
We had some very good reasons to choose CDI:</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>CDI is a mature and proven component model</p>
</li>
<li>
<p>We at Red Hat have almost ten years of experience with developing <a href="http://weld.cdi-spec.org/">Weld - the CDI Reference Implementation</a></p>
</li>
<li>
<p>The CDI API is built on top of <code>javax.inject</code> so that it should be easy to migrate from any DI framework compatible with <code>@Inject</code></p>
</li>
</ol>
</div>
<div class="paragraph">
<p>Our primary goal was to implement a supersonic build-time oriented DI solution compatible with CDI.
This would allow users to continue using CDI in their applications but also leverage Quarkus build-time optimizations.
However, ArC is not a full CDI implementation verified by the TCK - see also the list of <a href="https://quarkus.io/guides/cdi-reference#supported_features">supported features</a> and the list of <a href="https://quarkus.io/guides/cdi-reference#limitations">limitations</a>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="build-time-processing-benefits-and-drawbacks"><a class="anchor" href="#build-time-processing-benefits-and-drawbacks"></a>Build-time Processing Benefits and Drawbacks</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="fail-fast"><a class="anchor" href="#fail-fast"></a>Fail Fast</h3>
<div class="paragraph">
<p>Beans and dependencies are validated during the build so that your application can never fail in production with common problems such as <code>AmbiguousResolutionException</code> or <code>UnsatisfiedResolutionException</code>.</p>
</div>
</div>
<div class="sect2">
<h3 id="instant-startup"><a class="anchor" href="#instant-startup"></a>Instant Startup</h3>
<div class="paragraph">
<p>When the app starts ArC just loads all the metadata and initializes some internal structures.
There is no need to analyze the application classes again.
This means negligible startup overhead.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
This applies to both the GraalVM and OpenJDK HotSpot runtimes.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="minimized-runtime"><a class="anchor" href="#minimized-runtime"></a>Minimized Runtime</h3>
<div class="paragraph">
<p>In Quarkus 0.19, ArC plus integration runtime consist of 72 classes and occupies ~ 140 KB in jars.
<a href="http://weld.cdi-spec.org/">Weld 3.1.1</a> (CDI Reference Implementation) core is roughly 1200 classes and approx. 2 MB jar.
In other words, ArC runtime takes approx. 7% of the Weld runtime in terms of number of classes and jar footprint.</p>
</div>
</div>
<div class="sect2">
<h3 id="optimized-code-paths-and-metadata-structures"><a class="anchor" href="#optimized-code-paths-and-metadata-structures"></a>Optimized Code Paths and Metadata Structures</h3>
<div class="paragraph">
<p>When generating the metadata classes ArC can sometimes produce leaner and smarter logic because it has the whole application analyzed already.
This is one of the areas where we would like to develop and improve ArC.</p>
</div>
</div>
<div class="sect2">
<h3 id="extension-points"><a class="anchor" href="#extension-points"></a>Extension Points</h3>
<div class="paragraph">
<p>Unfortunately, CDI portable extensions are inherently runtime constructs and therefore cannot be fully supported in Quarkus.
In fact, all CDI extensions are ignored at the moment.
Nevertheless, most of the functionality can be achieved using <a href="https://quarkus.io/guides/cdi-reference#build-time-extension-points">Quarkus extensions</a>.
The CDI extensions are encouraged to generalize the code, and if possible provide a Quarkus extension to make full use of build-time metadata processing.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="non-standard-features"><a class="anchor" href="#non-standard-features"></a>Non-standard Features</h2>
<div class="sectionbody">
<div class="paragraph">
<p>ArC is not limited to standards and we&#8217;re constantly looking for ways to go beyond and extend the possibilities.
Following are some examples of non-standard features provided by Quarkus DI.</p>
</div>
<div class="sect2">
<h3 id="qualified-injected-fields"><a class="anchor" href="#qualified-injected-fields"></a>Qualified Injected Fields</h3>
<div class="paragraph">
<p>Normally, if you declare an injected field you&#8217;ll always need to use <code>@Inject</code> and optionally required qualifiers:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">  @Inject
  @ConfigProperty(name = "cool")
  String coolProperty;</code></pre>
</div>
</div>
<div class="paragraph">
<p>In Quarkus, you can skip the <code>@Inject</code> annotation completely if an injected field declares at least one qualifier:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">  @ConfigProperty(name = "cool")
  String coolProperty;</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<code>@Inject</code> is still required for constructor and method injection.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="simplified-constructor-injection"><a class="anchor" href="#simplified-constructor-injection"></a>Simplified Constructor Injection</h3>
<div class="paragraph">
<p>In CDI, a normal scoped bean must always declare a no-args constructor (this constructor is normally generated by the compiler unless you declare any other constructor).
However, this requirement complicates constructor injection - you would need to provide a dummy no-args constructor to make things work in CDI.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">@ApplicationScoped
public class MyCoolService {

  private SimpleProcessor processor;

  MyCoolService() { // dummy constructor needed
  }

  @Inject // constructor injection
  MyCoolService(SimpleProcessor processor) {
    this.processor = processor;
  }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>There is no need to declare dummy constructors for normal scoped bean in Quarkus - they are generated automatically.
Also if there&#8217;s only one constructor there is no need for <code>@Inject</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">@ApplicationScoped
public class MyCoolService {

  private SimpleProcessor processor;

  MyCoolService(SimpleProcessor processor) {
    this.processor = processor;
  }
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
We don&#8217;t generate a no-args constructor automatically if a bean class extends another class that does not declare a no-args constructor.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="default-beans"><a class="anchor" href="#default-beans"></a>Default Beans</h3>
<div class="paragraph">
<p>CDI has a feature called <a href="https://docs.jboss.org/cdi/spec/2.0/cdi-spec.html#alternatives">alternatives</a>.
Simply said a bean annotated with <code>@Alternative</code> and <code>@Priority</code> takes precedence over the non-alternative beans during type-safe resolution.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">class MyBean {
}

@Alternative
@Priority(1)
class MyAlternativeBean extends MyBean {
}

@Inject // MyAlternativeBean wins and is injected!
MyBean bean;</code></pre>
</div>
</div>
<div class="paragraph">
<p>So, what if a user wants to override a bean defined by a library/extension?
The bean would have to be marked as a CDI <code>@Alternative</code> that is enabled using the <code>@Priority</code> annotation.
Is there a simpler approach?
Yes, there is.
You can use a non-standard feature called "default beans".
In this case, a bean that can be overridden should be annotated with <code>@io.quarkus.arc.DefaultBean</code>.
And that&#8217;s it.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">@DefaultBean
class MyBean {
}

class MyOwnBean extends MyBean {
}

@Inject // MyOwnBean wins and is injected!
MyBean bean;</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="removing-unused-beans"><a class="anchor" href="#removing-unused-beans"></a>Removing Unused Beans</h3>
<div class="paragraph">
<p>GraalVM native image does a pretty good job when removing all classes that are not reachable from your application.
However, sometimes checking reachability is not enough.
Sometimes the framework itself must decide whether a component is needed or not.
In standard CDI, all beans are retained by the container no matter whether they&#8217;re needed or not.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s suppose we have a bean class <code>org.acme.Foo</code>.
This bean class imports and uses a lot of various classes.
It&#8217;s annotated with <code>@ApplicationScoped</code> and so Quarkus needs to generate a bean metadata class and a client proxy and register this metadata when the application starts.
But what if nobody ever uses this bean?
We would still hold a reference on the generated metadata, and the bean class itself, and its dependencies.
In other words, all these classes would be reachable.</p>
</div>
<div class="paragraph">
<p>Quarkus attempts to remove all <strong>unused beans</strong> during build by default.
This helps to reduce the number of generated classes and also the amount of memory needed at runtime.
But how do we actually detect an unused bean?
The rules are described in the <a href="https://quarkus.io/guides/cdi-reference#remove_unused_beans">reference guide</a> but simply said: if a bean is not injected anywhere and cannot be reached in any other standard way (e.g. observer notification) it is removed.
Moreover, users can instruct the container to not remove a bean by annotating the bean class with <code>@io.quarkus.arc.Unremovable</code>.
Finally, this optimization can be disabled and fine tuned by using the <code>quarkus.arc.remove-unused-beans</code> property.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
This feature applies to the JVM mode as well.
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
              
          </div>
          <div class="width-12-12"><div class="share-page">
  <a class="share-linkedin" href="https://www.linkedin.com/shareArticle?mini=true&url=https://quarkus.io/blog/quarkus-dependency-injection/&title=Quarkus Dependency Injection" rel="nofollow" target="_blank" title="Share on LinkedIn">
    <img src="/assets/images/share-page/icons_social-linkedin.png"/>
  </a>
  <a class="share-twitter" href="https://twitter.com/intent/tweet?text=Quarkus Dependency Injection&url=https://quarkus.io/blog/quarkus-dependency-injection/&via=quarkusio&related=quarkusio" rel="nofollow" target="_blank" title="Share on Twitter">
    <img src="/assets/images/share-page/icons_social-twitter.png"/>
  </a>
  <a class="share-facebook" href="https://facebook.com/sharer.php?u=https://quarkus.io/blog/quarkus-dependency-injection/" rel="nofollow" target="_blank" title="Share on Facebook">
    <img src="/assets/images/share-page/icons_social-facebook.png"/>
  </a>
  <a class="share-reddit" href="http://www.reddit.com/submit?url=https://quarkus.io/blog/quarkus-dependency-injection/" onclick="window.open(this.href, 'pop-up', 'left=20,top=20,width=900,height=500,toolbar=1,resizable=0'); return false;" title="Share on Reddit" >
    <img src="/assets/images/share-page/icons_social-reddit.png"/>
  </a>
  <a class="share-email" href="mailto:?subject=Quarkus Dependency Injection&amp;body=Quarkus Dependency Injection https://quarkus.io/blog/quarkus-dependency-injection/" title="Share via Email" >
    <img src="/assets/images/share-page/icons_social-email.png"/>
  </a>
</div>
</div>
        </div>
      </div>
    </div>
  </div>
</div>

  </div>

  <div class="content project-footer">
  <div class="footer-section">
    <div class="logo-wrapper">
      <a href="/"><img src="/assets/images/quarkus_logo_horizontal_rgb_reverse.svg" class="project-logo" title="Quarkus"></a>
    </div>
  </div>
  <div class="grid-wrapper">
    <p class="grid__item width-3-12">Quarkus is open. All dependencies of this project are available under the <a href='https://www.apache.org/licenses/LICENSE-2.0' target='_blank'>Apache Software License 2.0</a> or compatible license.<br /><br />This website was built with <a href='https://jekyllrb.com/' target='_blank'>Jekyll</a>, is hosted on <a href='https://pages.github.com/' target='_blank'>Github Pages</a> and is completely open source. If you want to make it better, <a href='https://github.com/quarkusio/quarkusio.github.io' target='_blank'>fork the website</a> and show us what you’ve got.</p>

    
      <div class="width-1-12 project-links">
        <span>Navigation</span>
        <ul class="footer-links width-1-12">
          
            <li><a href="/">Home</a></li>
          
            <li><a href="/guides">Guides</a></li>
          
            <li><a href="/community/#contributing">Contribute</a></li>
          
            <li><a href="/faq">FAQ</a></li>
          
            <li><a href="/get-started">Get Started</a></li>
          
        </ul>
      </div>
    
      <div class="width-1-12 project-links">
        <span>Contribute</span>
        <ul class="footer-links width-1-12">
          
            <li><a href="https://twitter.com/quarkusio">Follow us</a></li>
          
            <li><a href="https://github.com/quarkusio">GitHub</a></li>
          
            <li><a href="/security">Security&nbsp;policy</a></li>
          
        </ul>
      </div>
    
      <div class="width-1-12 project-links">
        <span>Get Help</span>
        <ul class="footer-links width-1-12">
          
            <li><a href="https://groups.google.com/forum/#!forum/quarkus-dev">Forums</a></li>
          
            <li><a href="https://quarkusio.zulipchat.com">Chatroom</a></li>
          
        </ul>
      </div>
    

    
      <div class="width-3-12 more-links">
        <span>Quarkus is made of community projects</span>
        <ul class="footer-links">
          
            <li><a href="https://vertx.io/" target="_blank">Eclipse Vert.x</a></li>
          
            <li><a href="https://microprofile.io" target="_blank">Eclipse MicroProfile</a></li>
          
            <li><a href="https://hibernate.org" target="_blank">Hibernate</a></li>
          
            <li><a href="https://netty.io" target="_blank">Netty</a></li>
          
            <li><a href="https://resteasy.github.io" target="_blank">RESTEasy</a></li>
          
            <li><a href="https://camel.apache.org" target="_blank">Apache Camel</a></li>
          
            <li><a href="https://code.quarkus.io/" target="_blank">And many more...</a></li>
          
        </ul>
      </div>
    
  </div>
</div>
  <div class="content redhat-footer">
  <div class="grid-wrapper">
    <span class="licence">
      <i class="fab fa-creative-commons"></i><i class="fab fa-creative-commons-by"></i> <a href="https://creativecommons.org/licenses/by/3.0/" target="_blank">CC by 3.0</a> | <a href="https://www.redhat.com/en/about/privacy-policy">Privacy Policy</a>
    </span>
    <span class="redhat">
      Sponsored by
    </span>
    <span class="redhat-logo">
      <a href="https://www.redhat.com/" target="_blank"><img src="/assets/images/redhat_reversed.svg"></a>
    </span>
  </div>
</div>


  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" integrity="sha384-8gBf6Y4YYq7Jx97PIqmTwLPin4hxIzQw5aDmUg/DDhul9fFpbbLcLh3nTIIDJKhx" crossorigin="anonymous"></script>
  <script type="text/javascript" src="/assets/javascript/mobile-nav.js"></script>
  <script type="text/javascript" src="/assets/javascript/scroll-down.js"></script>
  <script src="/assets/javascript/satellite.js" type="text/javascript"></script>
  <script src="https://quarkus.io/guides/javascript/config.js" type="text/javascript"></script>
  <script src="/assets/javascript/search-filter.js" type="text/javascript"></script>
  <script src="/assets/javascript/back-to-top.js" type="text/javascript"></script>
</body>

</html>
